package com.tripspins.app.helper;

import android.os.AsyncTask;
import android.util.Log;

import com.tripspins.app.bo.CurrentWeather;
import com.tripspins.app.interfaces.OnTaskCompleted;
import com.google.android.gms.maps.model.LatLng;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by João.Rutkoski on 20/06/13.
 */
public class WeatherHelper {

    OnTaskCompleted activity;

    public WeatherHelper(OnTaskCompleted activity) {

        this.activity = activity;
    }

    public void getWeather(LatLng latLng) {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append("http://api.worldweatheronline.com/free/v1/weather.ashx?q=");
        sbUrl.append(latLng.latitude + ",");
        sbUrl.append(latLng.longitude);
        sbUrl.append("&format=json&num_of_days=1&key=4mvpj9szbs7qk6r7qhgwcn3j");
        JsonParser json = new JsonParser();
        json.execute(new String[] { sbUrl.toString() });

    }

    class JsonParser extends AsyncTask<String, Void, CurrentWeather> {
        private int distance;

        @Override
        protected CurrentWeather doInBackground(String... params) {
            String httpResponse = readHttpGet(params[0]);
            CurrentWeather currWeather = new CurrentWeather();
            try {
                final JSONObject json = new JSONObject(httpResponse);
                final JSONObject jsonData = json.getJSONObject("data");
                final JSONObject jsonCurrentCondition = jsonData.getJSONArray("current_condition").getJSONObject(0);
                final JSONObject jsonDescription = jsonCurrentCondition.getJSONArray("weatherDesc").getJSONObject(0);
                final JSONObject jsonIconUrl = jsonCurrentCondition.getJSONArray("weatherIconUrl").getJSONObject(0);

                currWeather.setCloudCover(jsonCurrentCondition.getDouble("cloudcover"));
                currWeather.setHumidity(jsonCurrentCondition.getDouble("humidity"));
                currWeather.setPrecipMM(jsonCurrentCondition.getDouble("precipMM"));
                currWeather.setPressure(jsonCurrentCondition.getDouble("pressure"));
                currWeather.setTempC(jsonCurrentCondition.getDouble("temp_C"));
                currWeather.setTempF(jsonCurrentCondition.getDouble("temp_F"));
                currWeather.setVisibility(jsonCurrentCondition.getDouble("visibility"));
                currWeather.setWindDir16Point(jsonCurrentCondition.getString("winddir16Point"));
                currWeather.setWindDirDegree(jsonCurrentCondition.getInt("winddirDegree"));
                currWeather.setWindSpeedKmph(jsonCurrentCondition.getDouble("windspeedKmph"));
                currWeather.setWindspeedMiles(jsonCurrentCondition.getDouble("windspeedMiles"));
                currWeather.setWeatherDesc(jsonDescription.getString("value"));
                currWeather.setWeatherIconUrl(jsonIconUrl.getString("value"));


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return currWeather;
        }

        @Override
        protected void onPostExecute(CurrentWeather currWeather) {
            activity.onTaskCompleted(currWeather);
        }

        public String readHttpGet(String url) {

            StringBuilder builder = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            try {
                HttpResponse response = client.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                } else {
                    Log.e(this.getClass().toString(), "Failed to download file");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                Log.e("caralhou", e.toString());
                e.printStackTrace();
            }
            return builder.toString();

        }
    }


}
